import { Inject, Get, Query } from '@midwayjs/core';
import { CoolController, BaseController, TagTypes, CoolUrlTag } from '@cool-midway/core';
import { DeviceRequestLogEntity } from '../../entity/request-log';
import { DeviceRequestLogService } from '../../service/request-log';
import { DeviceInfoEntity } from '../../entity/info';

/**
 * 设备请求日志
 */
@CoolUrlTag({
  key: TagTypes.IGNORE_TOKEN,
  value: ['addLog']
})
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: DeviceRequestLogEntity,
  service: DeviceRequestLogService,
  pageQueryOp: {
    select: ['a.*', 'b.name as deviceName'],
    join: [
      {
        entity: DeviceInfoEntity,
        alias: 'b',
        condition: 'a.deviceId = b.id',
        type: 'leftJoin',
      },
    ],
    keyWordLikeFields: [],
    fieldEq: [{ column: 'a.deviceId', requestParam: 'deviceId' }],
    fieldLike: [],
    where: async ctx => {
      const { requestMethod, statusCode, processTime, requestTime } =
        ctx.request.body;
      const where = [];

      if (requestMethod && requestMethod.length > 0) {
        where.push([
          `a.requestMethod IN (:...requestMethod)`,
          { requestMethod },
        ]);
      }

      if (statusCode && statusCode.length === 2) {
        where.push([
          `a.statusCode BETWEEN :startStatusCode AND :endStatusCode`,
          { startStatusCode: statusCode[0], endStatusCode: statusCode[1] },
        ]);
      }

      if (processTime && processTime.length === 2) {
        where.push([
          `a.processTime BETWEEN :startProcessTime AND :endProcessTime`,
          { startProcessTime: processTime[0], endProcessTime: processTime[1] },
        ]);
      }

      if (requestTime && requestTime.length === 2) {
        where.push([
          `a.requestTime BETWEEN :startRequestTime AND :endRequestTime`,
          { startRequestTime: requestTime[0], endRequestTime: requestTime[1] },
        ]);
      }

      return where;
    },
  },
})
export class AdminDeviceRequestLogController extends BaseController {
  @Inject()
  deviceRequestLogService: DeviceRequestLogService;

  @Get('/addLog', { summary: '添加请求日志' })
  async addLog(@Query() param: { method: string; params: any }) {
    console.log('addLog', param);
    return this.ok(await this.deviceRequestLogService.addLog(param.method, param.params));
  }
}
